package com.blandware.atleap.webapp.taglib.core.menu.context;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/**
 * <p>Marks logical group of menu items, which are included in the context menu.
 * This tag is usable within various iteration tags to mark logical row of
 * generated table. This tag is needed, because context menu support tags need
 * to know where set of items corresponding to some data row ends and next set
 * begins.
 * <br />
 * This tag is only valid when nested within <em>contextMenu</em> tag.
 * </p>
 * <p><a href="ItemSetTag.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.5 $ $Date: 2006/08/03 10:08:25 $
 * @see ContextMenuTag
 * @see ItemTag
 * @jsp.tag name="itemSet"
 * body-content="scriptless"
 */
public class ItemSetTag extends SimpleTagSupport {

	// ~ Static fields

	/**
	 * Part of context key, under which number of this tag is stored. Full key is generated using ID of parent ContextMenuTag
	 */
	protected static final String INDEX_KEY_PART = "com.blandware.atleap.webapp.taglib.core.menu.context.ItemSetTag.INDEX";

	/**
	 * Index of currently processed row
	 */
	protected Integer index;

	/**
	 * Creates new instance of ItemSetTag
	 */
	public ItemSetTag() {
	}

    /**
     * Returns index of currently processed row
     *
     * @return index
     */
	public Integer getIndex() {
		return index;
	}

    /**
     * Processes the tag
     *
     * @throws JspException
     * @throws IOException
     */
	public void doTag() throws JspException, IOException {
		PageContext pageContext = (PageContext) getJspContext();

		// search for parent ContextMenuTag
		ContextMenuTag parentContextMenuTag = (ContextMenuTag) findAncestorWithClass(this, ContextMenuTag.class);

		if ( parentContextMenuTag == null ) {
			throw new JspTagException("This tag is only valid when nested within 'contextMenu' tag");
		}

		// search for index

		// construct key first
		String key = INDEX_KEY_PART + "[" + parentContextMenuTag.getTagId() + "]";

		// get index
		index = (Integer) pageContext.getAttribute(key, PageContext.REQUEST_SCOPE);
		if ( index == null ) {
			index = new Integer(0);
		} else {
			index = new Integer(index.intValue() + 1);
		}
		// save index in request
		pageContext.setAttribute(key, index, PageContext.REQUEST_SCOPE);

		// process body
		JspFragment body = getJspBody();
		if ( body != null ) {
			body.invoke(null);
		}

	}

}
